package com.ls.search;

import java.util.Arrays;

/**
 * 0.618
 * 斐波那契查找
 */
public class FibonacciSearch {
    int maxSize = 20;

    public static void main(String[] args) {
        int[] arr = {3, 7, 9, 9, 9, 9, 10, 10, 11};
        FibonacciSearch fibonacciSearch = new FibonacciSearch();
        System.out.println(
                fibonacciSearch.search(arr, 10)
        );


    }


    public int search(int[] arr, int value) {
        int low = 0;
        int high = arr.length - 1;
        int k = 0;//表示斐波那契分割数值的下标
        int mid = 0;
        int[] f = fib();

        while (high > f[k] - 1) {
            k++;
        }
        //因为f[k]值可能大于a的长度,因此我们需要使用Arrays类,构造一个新的数组,并指向arr[]
        int[] temp = Arrays.copyOf(arr, f[k]);
        //把后面的0全都变成最后一个值(最大值)
        for (int i = high - 1; i < temp.length; i++) {
            temp[i] = arr[high];
        }

        while (low <= high) {
            mid = low + f[k - 1] - 1;
            if (value < temp[mid]) {
                high = mid - 1;
                k--;
            } else if (value > temp[mid]) {
                low = mid + 1;
                k -= 2;
            } else {
                if (mid <= high) {
                    return mid;
                } else {
                    return high;
                }
            }
        }
        return -1;
    }


    //返回一个斐波那契数组
    public int[] fib() {
        int[] f = new int[maxSize];
        f[0] = 1;
        f[1] = 1;
        for (int i = 2; i < maxSize; i++) {
            f[i] = f[i - 1] + f[i - 2];
        }
        return f;
    }
}
